<template>
    <view class="container">
      <!-- 顶部搜索和统计 -->
      <view class="search-header">
        <view class="search-box">
          <u-search
            placeholder="搜索问题"
            v-model="searchText"
            :show-action="false"
            :clearabled="true"
            @search="handleSearch"
            @clear="handleSearch"
          ></u-search>
        </view>
        <view class="header-stats">
          <text class="stat-title">问答数</text>
          <text class="stat-value">{{ questionList.length }}</text>
        </view>
      </view>
  
      <!-- 问题分类筛选 -->
      <view class="filter-bar">
        <scroll-view scroll-x class="filter-scroll">
          <view class="filter-buttons">
            <view 
              v-for="item in filterTypes"
              :key="item.type"
              class="filter-btn" 
              :class="{ active: activeFilter === item.type }" 
              @click="setFilter(item.type)"
            >
              {{ item.label }}
            </view>
          </view>
        </scroll-view>
      </view>
  
      <!-- 问题列表 -->
      <view class="qa-list">
        <!-- 加载状态 -->
        <view class="loading" v-if="loading">
          <u-loading-icon></u-loading-icon>
        </view>
  
        <!-- 空状态 -->
        <view class="empty-state" v-else-if="!filteredQuestionList.length">
          <u-empty
            mode="data"
            text="暂无相关问题"
          ></u-empty>
        </view>
  
        <!-- 问答列表 -->
        <template v-else>
          <view class="qa-card" v-for="item in filteredQuestionList" :key="item.id">
            <view class="question-block">
              <view class="user-info">
                <u-avatar :src="item.userAvatar || '/static/default-avatar.png'" shape="circle" size="40"></u-avatar>
                <view class="user-details">
                  <text class="user-name">{{ item.nickname || '匿名用户' }}</text>
                  <view class="user-meta">
                    <text class="user-time">{{ item.createTime }}</text>
                    <text class="user-location" v-if="item.ipLocation">IP属地：{{ item.ipLocation }}</text>
                  </view>
                </view>
              </view>
              
              <view class="question-content">
                <view class="question-header">
                  <text class="question-title">{{ item.content }}</text>
                </view>
                <view class="question-desc" v-if="item.detail">
                  <text>{{ item.detail }}</text>
                </view>
              </view>
              
              <view class="question-footer">
                <view class="stats-info">
                  <text class="answer-count">{{ item.answerCount || 0 }}个回答</text>
                </view>
                <view class="action-btns">
                  <view class="action-btn" @click="handleLike(item)">
                    <u-icon :name="item.isLiked ? 'thumb-up-fill' : 'thumb-up'" size="20" :color="item.isLiked ? '#00b578' : '#999'"></u-icon>
                    <text :class="{ active: item.isLiked }">{{ item.likeCount || 0 }}</text>
                  </view>
                  <view class="action-btn" @click="showReplyInput(item.id)">
                    <u-icon name="chat" size="20" color="#999"></u-icon>
                    <text>回答</text>
                  </view>
                </view>
              </view>
            </view>
  
            <!-- 回答输入框 -->
            <view class="answer-input" v-if="item.isReplying">
              <view class="input-wrapper">
                <u-textarea
                  v-model="newAnswer"
                  placeholder="写下你的回答..."
                  :height="100"
                  :border="true"
                  :adjustPosition="false"
                  :focus="item.isReplying"
                  class="answer-textarea"
                ></u-textarea>
                <view class="input-actions">
                  <u-button size="mini" plain @click="cancelReply(item.id)">取消</u-button>
                  <u-button size="mini" type="primary" color="#00b578" @click="submitAnswer(item.id)">提交</u-button>
                </view>
              </view>
            </view>
          </view>
        </template>
      </view>
  
      <!-- 发起提问按钮 -->
      <view class="ask-question">
        <u-button type="primary" color="#00b578" icon="plus" @click="showAskModal">
          我要提问
        </u-button>
      </view>
  
      <!-- 提问弹窗 -->
      <u-popup 
        :show="askModalVisible" 
        mode="center" 
        round="10" 
        @close="hideAskModal"
        :maskCloseAble="false"
        :closeOnClickOverlay="false"
        :safeAreaInsetBottom="true"
        :customStyle="{
          maxHeight: '80vh',
          overflow: 'auto'
        }"
      >
        <view class="ask-modal">
          <view class="modal-header">
            <text class="modal-title">发起提问</text>
            <u-icon name="close" size="28" @click="hideAskModal" class="close-icon"></u-icon>
          </view>
          <view class="modal-content">
            <view class="input-item">
              <u-input
                v-model="newQuestion.content"
                placeholder="请输入问题内容"
                border="surround"
                clearable
                :adjustPosition="false"
                :focus="false"
                class="question-input"
              ></u-input>
            </view>
            <view class="input-item">
              <u-textarea
                v-model="newQuestion.detail"
                placeholder="请详细描述你的问题"
                :height="200"
                count
                :maxlength="500"
                class="question-textarea"
                :adjustPosition="false"
                :autoHeight="false"
                :fixed="true"
              ></u-textarea>
            </view>
          </view>
          <view class="modal-footer">
            <u-button plain @click="hideAskModal">取消</u-button>
            <u-button type="primary" color="#00b578" @click="submitQuestion">提交问题</u-button>
          </view>
        </view>
      </u-popup>
    </view>
  </template>
  
  <script setup>
  import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
  import { useAnswerStore } from '@/store/answerStore'
  import { storeToRefs } from 'pinia'
  import { onLoad } from '@dcloudio/uni-app'
  
  const answerStore = useAnswerStore()
  const { questionList, loading } = storeToRefs(answerStore)
  
  // 数据状态
  const searchText = ref('')
  const activeFilter = ref(0)
  const scrollTop = ref(0)
  const askModalVisible = ref(false)
  const newAnswer = ref('')
  const currentProductId = ref(null)
  
  // 新问题表单
  const newQuestion = ref({
    content: '',
    detail: '',
    fruitId: null
  })
  
  // 过滤类型定义
  const filterTypes = [
    { type: 0, label: '全部问题' },
    { type: 1, label: '热门问题' },
    { type: 2, label: '等待回答' },
    { type: 3, label: '我的提问' }
  ]
  
  // 根据筛选条件过滤问题列表
  const filteredQuestionList = computed(() => {
    let list = questionList.value || []
    
    // 搜索过滤
    if (searchText.value) {
      list = list.filter(item => 
        item.content.toLowerCase().includes(searchText.value.toLowerCase()) ||
        item.detail?.toLowerCase().includes(searchText.value.toLowerCase())
      )
    }
    
    // 分类过滤
    switch (activeFilter.value) {
      case 1:
        return list.sort((a, b) => (b.likeCount || 0) - (a.likeCount || 0))
      case 2:
        return list.filter(item => !item.answerCount || item.answerCount === 0)
      case 3:
        return list.filter(item => item.isOwner)
      default:
        return list
    }
  })
  
  // 加载问题列表
  const loadQuestionList = async (fruitId) => {
    try {
      const queryDTO = {
        fruitId: Number(fruitId),
        keyword: searchText.value.trim(),
        type: activeFilter.value
      }
      
      await answerStore.loadQuestionList(queryDTO)
    } catch (error) {
      uni.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  }
  
  // 搜索问题
  const handleSearch = () => {
    loadQuestionList(currentProductId.value)
  }
  
  // 设置过滤器
  const setFilter = (type) => {
    activeFilter.value = type
    loadQuestionList(currentProductId.value)
  }
  
  // 点赞问题
  const handleLike = async (item) => {
    if (!item.id) {
      uni.showToast({
        title: '问题ID无效',
        icon: 'none'
      })
      return
    }

    try {
      const result = await answerStore.toggleQuestionLike(item.id)
      if (result !== undefined) {
        uni.showToast({
          title: result ? '点赞成功' : '取消点赞',
          icon: 'success'
        })
      }
    } catch (error) {
      uni.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  }
  
  // 显示回复输入框
  const showReplyInput = (id) => {
    const question = questionList.value.find(item => item.id === id)
    if (question) {
      question.isReplying = true
    }
  }
  
  // 取消回复
  const cancelReply = (id) => {
    const question = questionList.value.find(item => item.id === id)
    if (question) {
      question.isReplying = false
      newAnswer.value = ''
    }
  }
  
  // 提交回答
  const submitAnswer = async (questionId) => {
    if (!newAnswer.value.trim()) {
      uni.showToast({
        title: '回答内容不能为空',
        icon: 'none'
      })
      return
    }
    
    try {
      const answerDTO = {
        questionId: questionId,
        content: newAnswer.value.trim()
      }
      
      const result = await answerStore.submitNewAnswer(answerDTO)
      if (result) {
        // 重置输入框并关闭回复区域
        newAnswer.value = ''
        cancelReply(questionId)
        
        uni.showToast({
          title: '回答已提交',
          icon: 'success'
        })
        
        // 刷新问题列表
        await loadQuestionList(currentProductId.value)
      }
    } catch (error) {
      uni.showToast({
        title: '提交失败',
        icon: 'none'
      })
    }
  }
  
  // 打开提问弹窗
  const showAskModal = () => {
    askModalVisible.value = true
    newQuestion.value = {
      content: '',
      detail: '',
      fruitId: currentProductId.value
    }
  }
  
  // 关闭提问弹窗
  const hideAskModal = () => {
    askModalVisible.value = false
    newQuestion.value = {
      content: '',
      detail: '',
      fruitId: null
    }
  }
  
  // 提交问题
  const submitQuestion = async () => {
    if (!newQuestion.value.content.trim()) {
      uni.showToast({
        title: '问题内容不能为空',
        icon: 'none'
      })
      return
    }
    
    try {
      const questionDTO = {
        content: newQuestion.value.content.trim(),
        detail: newQuestion.value.detail.trim(),
        fruitId: currentProductId.value
      }
      
      const result = await answerStore.submitNewQuestion(questionDTO)
      if (result) {
        // 重置表单并关闭弹窗
        hideAskModal()
        
        uni.showToast({
          title: '提问成功',
          icon: 'success'
        })
        
        // 刷新问题列表
        await loadQuestionList(currentProductId.value)
      }
    } catch (error) {
      uni.showToast({
        title: '提交失败',
        icon: 'none'
      })
    }
  }
  
  // 监听页面滚动
  const handlePageScroll = (e) => {
    scrollTop.value = e.scrollTop
  }
  
  onMounted(() => {
    uni.onPageScroll(handlePageScroll)
  })
  
  onBeforeUnmount(() => {
    uni.offPageScroll(handlePageScroll)
    // 清理数据
    answerStore.clearAll()
  })
  
  // 在页面加载时获取问题列表
  onLoad(async (options) => {
    const productId = options.productId
    if (!productId) {
      uni.showToast({
        title: '商品ID不能为空',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
      return
    }
    
    currentProductId.value = productId
    await loadQuestionList(productId)
  })
  </script>
  
  <style lang="scss" scoped>
  @import '@/styles/mixins.scss';
  @import '@/styles/variables.scss';
  
  .container {
    min-height: 100vh;
    background-color: $bg-color;
    padding-bottom: 120rpx;
  }
  
  // 搜索头部
  .search-header {
    background-color: #fff;
    padding: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .header-stats {
      margin-top: 16rpx;
      display: flex;
      align-items: center;
      
      .stat-title {
        font-size: 26rpx;
        color: $text-color-secondary;
        margin-right: 10rpx;
      }
      
      .stat-value {
        font-size: 28rpx;
        font-weight: bold;
        color: $text-color;
      }
    }
  }
  
  .search-box {
    margin-bottom: 16rpx;
  }
  
  // 过滤按钮
  .filter-bar {
    position: sticky;
    top: 0;
    z-index: 10;
    background-color: #fff;
    padding: 20rpx 0;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  }
  
  .filter-scroll {
    white-space: nowrap;
  }
  
  .filter-buttons {
    display: inline-flex;
    padding: 0 20rpx;
  }
  
  .filter-btn {
    display: inline-block;
    margin: 0 10rpx;
    padding: 12rpx 24rpx;
    border-radius: 30rpx;
    font-size: 26rpx;
    color: $text-color;
    background-color: $bg-color-light;
    transition: all 0.3s;
    
    &.active {
      background-color: rgba(0, 181, 120, 0.1);
      color: #00b578;
      font-weight: bold;
    }
  }
  
  // 问答列表
  .qa-list {
    padding: 20rpx;
    padding-bottom: 120rpx;
  }
  
  .qa-card {
    margin-bottom: 30rpx;
    background-color: #fff;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  }
  
  .question-block {
    padding: 20rpx;
  }
  
  .user-info {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;
  }
  
  .user-details {
    margin-left: 16rpx;
    
    .user-name {
      font-size: 28rpx;
      color: $text-color;
      font-weight: bold;
      margin-bottom: 4rpx;
    }
    
    .user-meta {
      display: flex;
      flex-wrap: wrap;
      gap: 10rpx;
      
      .user-time, .user-location {
        font-size: 22rpx;
        color: $text-color-secondary;
      }
    }
  }
  
  .question-content {
    margin-bottom: 16rpx;
  }
  
  .question-header {
    margin-bottom: 12rpx;
    
    .question-title {
      font-size: 30rpx;
      color: $text-color;
      line-height: 1.4;
    }
  }
  
  .question-desc {
    font-size: 28rpx;
    color: $text-color-secondary;
    line-height: 1.6;
  }
  
  .question-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16rpx;
  }
  
  .stats-info {
    display: flex;
    gap: 20rpx;
    
    .answer-count {
      font-size: 24rpx;
      color: $text-color-secondary;
    }
  }
  
  .action-btns {
    display: flex;
    gap: 20rpx;
  }
  
  .action-btn {
    display: flex;
    align-items: center;
    
    text {
      font-size: 24rpx;
      color: $text-color-secondary;
      margin-left: 6rpx;
      
      &.active {
        color: #00b578;
      }
    }
  }
  
  // 回答输入框
  .answer-input {
    padding: 20rpx;
    background-color: $bg-color-light;
    border-top: 1px solid $border-color-light;
    
    .input-wrapper {
      background-color: #fff;
      border-radius: 8rpx;
      padding: 20rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    }
    
    .answer-textarea {
      width: 100%;
      background-color: #fff;
      border: 1px solid $border-color;
      border-radius: 8rpx;
      padding: 16rpx;
      margin-bottom: 16rpx;
    }
    
    .input-actions {
      display: flex;
      justify-content: flex-end;
      gap: 16rpx;
      margin-top: 16rpx;
    }
  }
  
  // 加载和空状态
  .loading, .empty-state {
    padding: 40rpx 0;
    text-align: center;
    color: $text-color-secondary;
    font-size: 28rpx;
  }
  
  // 发起提问按钮
  .ask-question {
    position: fixed;
    right: 30rpx;
    bottom: 40rpx;
    z-index: 100;
    width: 180rpx;
    height: 70rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 181, 120, 0.3);
    border-radius: 35rpx;
    overflow: hidden;
    
    u-button {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      background-color: #00b578;
    }
  }
  
  // 提问弹窗
  .ask-modal {
    width: 650rpx;
    padding: 30rpx;
    border-radius: 12rpx;
    background-color: #fff;
    
    .modal-header {
      margin-bottom: 24rpx;
      text-align: center;
      position: relative;
      
      .modal-title {
        font-size: 32rpx;
        font-weight: bold;
        color: $text-color;
      }

      .close-icon {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        padding: 10rpx;
      }
    }
    
    .modal-content {
      margin-bottom: 24rpx;
      
      .input-item {
        margin-bottom: 20rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
      
      .question-input {
        background-color: #fff;
        border: 1px solid $border-color;
        border-radius: 8rpx;
        
        :deep(.u-input__input) {
          padding: 16rpx;
        }
      }
      
      .question-textarea {
        background-color: #fff;
        border: 1px solid $border-color;
        border-radius: 8rpx;
        padding: 16rpx;
      }
    }
    
    .modal-footer {
      display: flex;
      justify-content: space-between;
      gap: 20rpx;
      padding-top: 20rpx;
      border-top: 1px solid $border-color-light;
    }
  }
  
  // 响应式适配
  @media screen and (max-width: 375px) {
    .question-title {
      font-size: 28rpx;
    }
    
    .question-desc {
      font-size: 26rpx;
    }
    
    .answer-content {
      font-size: 24rpx;
    }
  }
  
  // 修改点赞图标颜色
  :deep(.u-icon) {
    &.liked {
      color: #00b578;
    }
  }
  </style>